
// 专业滤镜算法

ç


// 专业级黑白滤镜（ITU-R BT.601标准）
export const applyGrayscale = async (canvasId, width, height, componentInstance) => {
    try {
        // 1. 安全获取图像数据
        const { data: buffer } = await new Promise((resolve, reject) => {
            uni.canvasGetImageData({
                canvasId,
                x: 0,
                y: 0,
                width,
                height,
                success: resolve,
                fail: reject
            }, componentInstance);
        });
        // 2. 创建类型安全视图
        const srcData = new Uint8ClampedArray(buffer);
        const destData = new Uint8ClampedArray(buffer.byteLength); // 创建独立缓冲区

        // 

        for (let i = 0; i < srcData.length; i += 4) {
            const r = srcData[i];
            const g = srcData[i + 1];
            const b = srcData[i + 2];
            
            // ITU-R BT.601 标准灰度计算
            const y = 0.299 * r + 0.587 * g + 0.114 * b;
            
            destData[i] = y;     // R
            destData[i + 1] = y; // G
            destData[i + 2] = y; // B
            destData[i + 3] = srcData[i + 3]; // Alpha
        }

        // 4. 内存验证
        if (destData.length !== width * height * 4) {
            throw new Error(`数据长度异常: 预期 ${width * height * 4}, 实际 ${destData.length}`);
        }

        // 5. 安全写入
        await new Promise((resolve, reject) => {
            uni.canvasPutImageData({
                canvasId,
                x: 0,
                y: 0,
                width,
                height,
                data: destData,
                success: resolve,
                fail: reject
            }, componentInstance);
        });
    } catch (err) {
        console.error('专业级黑白滤镜:', err);
        throw new Error('FILTER_PROCESS_FAIL');
    }

};

// 电影级冷调滤镜[intensity=1.2] - 冷调强度 (0.0~2.0)
export const applyCoolTone = async (canvasId, width, height, componentInstance, intensity = 1.2) => {
    try {
        // 1. 安全获取图像数据
        const { data: buffer } = await new Promise((resolve, reject) => {
            uni.canvasGetImageData({
                canvasId,
                x: 0,
                y: 0,
                width,
                height,
                success: resolve,
                fail: reject
            }, componentInstance);
        });
        // 2. 创建类型安全视图
        const srcData = new Uint8ClampedArray(buffer);
        const destData = new Uint8ClampedArray(buffer.byteLength); // 创建独立缓冲区

        // 冷调增强算法
    const clamp = (v) => Math.min(255, Math.max(0, v));

    // ASC-CDL 参数动态计算（根据强度插值）
    const rCoeff = 0.88 - 0.1 * intensity;  // 红色衰减系数
    const bBoost = 0.12 + 0.08 * intensity; // 蓝色增强系数

    for (let i = 0; i < srcData.length; i += 4) {
        const r = srcData[i];
        const g = srcData[i + 1];
        const b = srcData[i + 2];

        // 通道混合公式
        const newR = r * rCoeff + g * (-0.02) + b * bBoost;
        const newG = r * 0.02 + g * 0.97 + b * 0.04;
        const newB = r * (-0.04) + g * 0.12 + b * (1.08 + 0.1 * intensity);

        // 暗部青蓝色偏 (V = 0.3R + 0.6G + 0.1B)
        const luminance = 0.3 * r + 0.6 * g + 0.1 * b;
        const shadowBias = Math.pow(1.0 - luminance / 255, 2) * 20 * intensity;
        
        destData[i] = clamp(newR - shadowBias * 0.3);      // R
        destData[i + 1] = clamp(newG - shadowBias * 0.2);  // G
        destData[i + 2] = clamp(newB + shadowBias);        // B
        destData[i + 3] = srcData[i + 3];                // Alpha
    }

        // 4. 内存验证
        if (destData.length !== width * height * 4) {
            throw new Error(`数据长度异常: 预期 ${width * height * 4}, 实际 ${destData.length}`);
        }

        // 5. 安全写入
        await new Promise((resolve, reject) => {
            uni.canvasPutImageData({
                canvasId,
                x: 0,
                y: 0,
                width,
                height,
                data: destData,
                success: resolve,
                fail: reject
            }, componentInstance);
        });
    } catch (err) {
        console.error('电影级冷调滤镜:', err);
        throw new Error('FILTER_PROCESS_FAIL');
    }
};
//暖阳
export const applyWarmSunlight = async (canvasId, width, height, componentInstance) => {
    try {
        // 1. 获取原始图像数据
        const { data: buffer } = await new Promise((resolve, reject) => {
            uni.canvasGetImageData({
                canvasId,
                x: 0,
                y: 0,
                width,
                height,
                success: resolve,
                fail: reject
            }, componentInstance);
        });

        // 2. 创建处理缓冲区
        const srcData = new Uint8ClampedArray(buffer);
        const destData = new Uint8ClampedArray(buffer.byteLength);

        // 3. 预计算色相矩阵（-10度）
        const θ = -10 * Math.PI / 180;
        const cosθ = Math.cos(θ);
        const sinθ = Math.sin(θ);
        const hueMatrix = [
            0.213 + cosθ*0.787 + sinθ*(-0.213),
            0.715 + cosθ*(-0.715) + sinθ*(-0.715),
            0.072 + cosθ*(-0.072) + sinθ*(0.928),
            
            0.213 + cosθ*(-0.213) + sinθ*(0.143),
            0.715 + cosθ*(0.285) + sinθ*(0.140),
            0.072 + cosθ*(-0.072) + sinθ*(-0.283),
            
            0.213 + cosθ*(-0.213) + sinθ*(-0.787),
            0.715 + cosθ*(-0.715) + sinθ*(0.715),
            0.072 + cosθ*(0.928) + sinθ*(0.072)
        ];

        // 4. 精准处理流水线
        for (let i = 0; i < srcData.length; i += 4) {
            let r = srcData[i], g = srcData[i+1], b = srcData[i+2];

            // Step 1: 棕褐色效果（30%强度）
            const sepiaR = (r * 0.393 + g * 0.769 + b * 0.189) * 0.3 + r * 0.7;
            const sepiaG = (r * 0.349 + g * 0.686 + b * 0.168) * 0.3 + g * 0.7;
            const sepiaB = (r * 0.272 + g * 0.534 + b * 0.131) * 0.3 + b * 0.7;
            r = sepiaR, g = sepiaG, b = sepiaB;

            // Step 2: 亮度提升（5%）
            r *= 1.05;
            g *= 1.05;
            b *= 1.05;

            // Step 3: 饱和度增强（20%）
            const gray = 0.2126*r + 0.7152*g + 0.0722*b;
            r = gray + (r - gray) * 1.2;
            g = gray + (g - gray) * 1.2;
            b = gray + (b - gray) * 1.2;

            // Step 4: 色相旋转（-10度）
            const nr = r*hueMatrix[0] + g*hueMatrix[1] + b*hueMatrix[2];
            const ng = r*hueMatrix[3] + g*hueMatrix[4] + b*hueMatrix[5];
            const nb = r*hueMatrix[6] + g*hueMatrix[7] + b*hueMatrix[8];

            // 最终值处理
            destData[i] = Math.min(255, Math.max(0, nr));  // R
            destData[i+1] = Math.min(255, Math.max(0, ng));// G
            destData[i+2] = Math.min(255, Math.max(0, nb));// B
            destData[i+3] = srcData[i+3]; // Alpha
        }

        // 5. 写入画布
        await new Promise((resolve, reject) => {
            uni.canvasPutImageData({
                canvasId,
                x: 0,
                y: 0,
                width,
                height,
                data: destData,
                success: resolve,
                fail: reject
            }, componentInstance);
        });
    } catch (err) {
        console.error('精准滤镜处理失败:', err);
        throw new Error('FILTER_ACCURACY_ERROR');
    }
};

//小清新
export const applyFreshFilter = async (canvasId, width, height, componentInstance) => {
    try {
        // 1. 安全获取原始图像数据
        const { data: buffer } = await new Promise((resolve, reject) => {
            uni.canvasGetImageData({
                canvasId,
                x: 0,
                y: 0,
                width,
                height,
                success: resolve,
                fail: reject
            }, componentInstance);
        });

        // 2. 创建双缓冲处理
        const srcData = new Uint8ClampedArray(buffer);
        const destData = new Uint8ClampedArray(buffer.byteLength);

        // 预计算色相旋转矩阵（15度）
        const θ = Math.PI * 15 / 180;
        const cosθ = Math.cos(θ);
        const sinθ = Math.sin(θ);
        const lumR = 0.2126, lumG = 0.7152, lumB = 0.0722;
        const hueRotateMatrix = [
            lumR + cosθ*(1 - lumR) + sinθ*(-lumR),
            lumG + cosθ*(-lumG) + sinθ*(-lumG),
            lumB + cosθ*(-lumB) + sinθ*(1 - lumB),
            
            lumR + cosθ*(-lumR) + sinθ*(0.143),
            lumG + cosθ*(1 - lumG) + sinθ*(0.140),
            lumB + cosθ*(-lumB) + sinθ*(-0.283),
            
            lumR + cosθ*(-lumR) + sinθ*(-(1 - lumR)),
            lumG + cosθ*(-lumG) + sinθ*(lumG),
            lumB + cosθ*(1 - lumB) + sinθ*(lumB)
        ];

        // 3. 工业级像素处理流水线
        for (let i = 0; i < srcData.length; i += 4) {
            let r = srcData[i], g = srcData[i+1], b = srcData[i+2];
            
            // 亮度增强 (1.1)
            r *= 1.1;
            g *= 1.1;
            b *= 1.1;

            // 对比度调整 (0.95)
            r = (r - 128) * 0.95 + 128;
            g = (g - 128) * 0.95 + 128;
            b = (b - 128) * 0.95 + 128;

            // 饱和度增强 (1.2)
            const gray = 0.2126 * r + 0.7152 * g + 0.0722 * b;
            r = gray + (r - gray) * 1.2;
            g = gray + (g - gray) * 1.2;
            b = gray + (b - gray) * 1.2;

            // 色相旋转 (15deg)
            const nr = r * hueRotateMatrix[0] + g * hueRotateMatrix[1] + b * hueRotateMatrix[2];
            const ng = r * hueRotateMatrix[3] + g * hueRotateMatrix[4] + b * hueRotateMatrix[5];
            const nb = r * hueRotateMatrix[6] + g * hueRotateMatrix[7] + b * hueRotateMatrix[8];

            // 最终钳制与写入
            destData[i] = Math.min(255, Math.max(0, nr));  // R
            destData[i+1] = Math.min(255, Math.max(0, ng));// G
            destData[i+2] = Math.min(255, Math.max(0, nb));// B
            destData[i+3] = srcData[i+3]; // Alpha保留
        }

        // 4. 数据完整性校验
        if (destData.length !== width * height * 4) {
            throw new Error(`Buffer validation failed: Expected ${width*height*4}, got ${destData.length}`);
        }

        // 5. 安全写回画布
        await new Promise((resolve, reject) => {
            uni.canvasPutImageData({
                canvasId,
                x: 0,
                y: 0,
                width,
                height,
                data: destData,
                success: resolve,
                fail: reject
            }, componentInstance);
        });
    } catch (err) {
        console.error('滤镜处理失败:', err);
        throw new Error('FILTER_PIPELINE_ERROR');
    }
};



